"""
任务API路由
"""

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List, Optional
from pydantic import BaseModel

from ..core.database import get_db, ScheduledTask
from ..core.logger import app_logger
from ..schedulers.tasks import (
    scrape_hot_trends,
    generate_content,
    publish_content,
    auto_workflow,
    cleanup_old_data,
    health_check
)

router = APIRouter()


class CreateTaskRequest(BaseModel):
    """创建任务请求模型"""
    task_name: str
    task_type: str  # scrape, generate, publish
    parameters: Optional[dict] = {}
    schedule: str  # cron表达式
    enabled: bool = True


@router.get("/", summary="获取任务列表")
async def get_tasks(
    task_type: Optional[str] = None,
    enabled: Optional[bool] = None,
    db: Session = Depends(get_db)
):
    """获取定时任务列表"""
    
    query = db.query(ScheduledTask)
    
    if task_type:
        query = query.filter(ScheduledTask.task_type == task_type)
    
    if enabled is not None:
        query = query.filter(ScheduledTask.enabled == enabled)
    
    tasks = query.order_by(ScheduledTask.created_at.desc()).all()
    
    return {
        "status": "success",
        "data": [
            {
                "id": task.id,
                "task_name": task.task_name,
                "task_type": task.task_type,
                "parameters": task.parameters,
                "schedule": task.schedule,
                "enabled": task.enabled,
                "last_run": task.last_run.isoformat() if task.last_run else None,
                "next_run": task.next_run.isoformat() if task.next_run else None,
                "created_at": task.created_at.isoformat()
            }
            for task in tasks
        ],
        "total": len(tasks)
    }


@router.post("/", summary="创建任务")
async def create_task(
    request: CreateTaskRequest,
    db: Session = Depends(get_db)
):
    """创建新的定时任务"""
    
    try:
        task = ScheduledTask(
            task_name=request.task_name,
            task_type=request.task_type,
            parameters=str(request.parameters) if request.parameters else "",
            schedule=request.schedule,
            enabled=request.enabled
        )
        
        db.add(task)
        db.commit()
        db.refresh(task)
        
        app_logger.info(f"创建任务成功: {request.task_name}")
        
        return {
            "status": "success",
            "message": "任务创建成功",
            "task_id": task.id
        }
        
    except Exception as e:
        app_logger.error(f"创建任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"创建任务失败: {str(e)}")


@router.put("/{task_id}", summary="更新任务")
async def update_task(
    task_id: int,
    request: CreateTaskRequest,
    db: Session = Depends(get_db)
):
    """更新现有任务"""
    
    task = db.query(ScheduledTask).filter(ScheduledTask.id == task_id).first()
    if not task:
        raise HTTPException(status_code=404, detail="任务不存在")
    
    try:
        task.task_name = request.task_name
        task.task_type = request.task_type
        task.parameters = str(request.parameters) if request.parameters else ""
        task.schedule = request.schedule
        task.enabled = request.enabled
        
        db.commit()
        
        app_logger.info(f"更新任务成功: {task_id}")
        
        return {
            "status": "success",
            "message": "任务更新成功"
        }
        
    except Exception as e:
        app_logger.error(f"更新任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"更新任务失败: {str(e)}")


@router.delete("/{task_id}", summary="删除任务")
async def delete_task(
    task_id: int,
    db: Session = Depends(get_db)
):
    """删除任务"""
    
    task = db.query(ScheduledTask).filter(ScheduledTask.id == task_id).first()
    if not task:
        raise HTTPException(status_code=404, detail="任务不存在")
    
    try:
        db.delete(task)
        db.commit()
        
        app_logger.info(f"删除任务成功: {task_id}")
        
        return {
            "status": "success",
            "message": "任务删除成功"
        }
        
    except Exception as e:
        app_logger.error(f"删除任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"删除任务失败: {str(e)}")


@router.post("/{task_id}/toggle", summary="启用/禁用任务")
async def toggle_task(
    task_id: int,
    db: Session = Depends(get_db)
):
    """切换任务启用状态"""
    
    task = db.query(ScheduledTask).filter(ScheduledTask.id == task_id).first()
    if not task:
        raise HTTPException(status_code=404, detail="任务不存在")
    
    try:
        task.enabled = not task.enabled
        db.commit()
        
        status_text = "启用" if task.enabled else "禁用"
        app_logger.info(f"任务 {task_id} {status_text}成功")
        
        return {
            "status": "success",
            "message": f"任务已{status_text}",
            "enabled": task.enabled
        }
        
    except Exception as e:
        app_logger.error(f"切换任务状态失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"操作失败: {str(e)}")


@router.post("/run/{task_type}", summary="手动执行任务")
async def run_task_manually(
    task_type: str,
    task_params: Optional[dict] = None
):
    """手动执行指定类型的任务"""
    
    if not task_params:
        task_params = {}
    
    try:
        # 定义可用的任务类型
        available_tasks = {
            "scrape": scrape_hot_trends,
            "generate": generate_content,
            "publish": publish_content,
            "workflow": auto_workflow,
            "cleanup": cleanup_old_data,
            "health": health_check
        }
        
        if task_type not in available_tasks:
            raise HTTPException(
                status_code=400, 
                detail=f"不支持的任务类型: {task_type}"
            )
        
        task_func = available_tasks[task_type]
        
        # 根据任务类型传递参数
        if task_type == "scrape":
            task = task_func.delay(task_params.get("sources", ["weibo", "zhihu", "baidu"]))
        elif task_type == "generate":
            if "trend_id" not in task_params:
                raise HTTPException(status_code=400, detail="generate任务需要trend_id参数")
            task = task_func.delay(
                task_params["trend_id"],
                task_params.get("platforms", ["weibo", "twitter"]),
                task_params.get("style", "default")
            )
        elif task_type == "publish":
            if "content_id" not in task_params:
                raise HTTPException(status_code=400, detail="publish任务需要content_id参数")
            task = task_func.delay(task_params["content_id"])
        else:
            # 其他任务不需要参数
            task = task_func.delay()
        
        app_logger.info(f"手动执行任务: {task_type}, 任务ID: {task.id}")
        
        return {
            "status": "success",
            "message": "任务已提交执行",
            "task_id": task.id,
            "task_type": task_type
        }
        
    except Exception as e:
        app_logger.error(f"手动执行任务失败: {e}")
        raise HTTPException(status_code=500, detail=f"执行任务失败: {str(e)}")


@router.get("/status/{task_id}", summary="查询任务状态")
async def get_task_status(task_id: str):
    """查询任务执行状态"""
    
    try:
        from ..schedulers.celery_app import celery_app
        
        # 获取任务状态
        task_result = celery_app.AsyncResult(task_id)
        
        response = {
            "task_id": task_id,
            "status": task_result.status,
            "current": task_result.info.get("current", 0) if isinstance(task_result.info, dict) else 0,
            "total": task_result.info.get("total", 1) if isinstance(task_result.info, dict) else 1,
        }
        
        if task_result.status == "SUCCESS":
            response["result"] = task_result.result
        elif task_result.status == "FAILURE":
            response["error"] = str(task_result.info)
        elif task_result.status == "PROGRESS":
            response["info"] = task_result.info
        
        return {
            "status": "success",
            "data": response
        }
        
    except Exception as e:
        app_logger.error(f"查询任务状态失败: {e}")
        raise HTTPException(status_code=500, detail=f"查询失败: {str(e)}")


@router.get("/available", summary="获取可用任务类型")
async def get_available_tasks():
    """获取所有可用的任务类型"""
    
    available_tasks = [
        {
            "type": "scrape",
            "name": "热点抓取",
            "description": "从各个平台抓取热点内容",
            "parameters": {
                "sources": "数据源列表 (weibo, zhihu, baidu)"
            }
        },
        {
            "type": "generate",
            "name": "内容生成",
            "description": "基于热点生成平台适配内容",
            "parameters": {
                "trend_id": "热点ID (必需)",
                "platforms": "平台列表 (weibo, twitter, wechat)",
                "style": "生成风格 (default, formal, casual, humorous)"
            }
        },
        {
            "type": "publish",
            "name": "内容发布",
            "description": "发布生成的内容到对应平台",
            "parameters": {
                "content_id": "内容ID (必需)"
            }
        },
        {
            "type": "workflow",
            "name": "自动化流程",
            "description": "执行完整的自动化工作流程",
            "parameters": {}
        },
        {
            "type": "cleanup",
            "name": "数据清理",
            "description": "清理过期的数据",
            "parameters": {}
        },
        {
            "type": "health",
            "name": "健康检查",
            "description": "检查系统运行状态",
            "parameters": {}
        }
    ]
    
    return {
        "status": "success",
        "tasks": available_tasks
    }